package org.asiainfo.gateway.filter;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HtmlUtil;
import io.netty.buffer.ByteBufAllocator;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import org.asiainfo.common.core.utils.StringUtils;
import org.asiainfo.gateway.config.properties.XssProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;

/**
 * 跨站脚本过滤器
 *
 * @author dotor-ww
 */
@Component
@ConditionalOnProperty(value = "security.xss.enabled", havingValue = "true")
@RequiredArgsConstructor
public class XssFilter implements GlobalFilter, Ordered {

    private final XssProperties xssProperties;

    /**
     * xss 过滤器
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //xss是否开启
        if (!xssProperties.getEnabled()) {
            return chain.filter(exchange);
        }
        //GET DELETE不过滤
        ServerHttpRequest request = exchange.getRequest();
        HttpMethod method = request.getMethod();
        if (ObjectUtil.isNull(method) || method == HttpMethod.GET || method == HttpMethod.DELETE)
            return chain.filter(exchange);
        //不过滤非JSON
        if (!isJsonRequest(exchange)) {
            return chain.filter(exchange);
        }
        //放行地址
        String url = request.getURI().getPath();
        if (StringUtils.matches(url, xssProperties.getExcludeUrls())) {
            return chain.filter(exchange);
        }
        //解析过滤
        ServerHttpRequestDecorator serverHttpRequestDecorator = requestDecorator(exchange);
        return chain.filter(exchange.mutate().request(serverHttpRequestDecorator).build());
    }

    /**
     * 是否是JSON请求
     *
     * @param exchange http请求
     * @return 结果
     */
    public boolean isJsonRequest(ServerWebExchange exchange) {
        String header = exchange.getRequest().getHeaders().getFirst(HttpHeaders.CONTENT_TYPE);
        return StringUtils.startsWithIgnoreCase(header, MediaType.APPLICATION_JSON_VALUE);
    }

    /**
     * 请求装饰器
     *
     * @param exchange http请求
     * @return ServerHttpRequestDecorator
     */
    public ServerHttpRequestDecorator requestDecorator(ServerWebExchange exchange) {
        return new ServerHttpRequestDecorator(exchange.getRequest()) {

            @NotNull
            @Override
            public Flux<DataBuffer> getBody() {
                //获取原始请求体的 Flux<DataBuffer> 对象
                Flux<DataBuffer> body = super.getBody();
                //数据缓冲区进行分块处理
                return body.buffer().map(dataBuffers -> {
                    //合并为一个完整的字节数组
                    DataBufferFactory dataBufferFactory = new DefaultDataBufferFactory();
                    DataBuffer join = dataBufferFactory.join(dataBuffers);
                    byte[] content = new byte[join.readableByteCount()];
                    join.read(content);
                    DataBufferUtils.release(join);
                    String bodyStr = new String(content, StandardCharsets.UTF_8);
                    // 防xss攻击过滤
                    bodyStr = HtmlUtil.cleanHtmlTag(bodyStr);
                    // 转成字节
                    byte[] bytes = bodyStr.getBytes();
                    NettyDataBufferFactory nettyDataBufferFactory = new NettyDataBufferFactory(ByteBufAllocator.DEFAULT);
                    //DataBuffer对象
                    DataBuffer buffer = nettyDataBufferFactory.allocateBuffer(bytes.length);
                    //字节数组写入
                    buffer.write(bytes);
                    return buffer;
                });
            }

            @NotNull
            @Override
            public HttpHeaders getHeaders() {
                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.putAll(super.getHeaders());
                // 由于修改了请求体的body，导致content-length长度不确定，因此需要删除原先的content-length
                httpHeaders.remove(HttpHeaders.CONTENT_LENGTH);
                //请求体以分块传输的方式进行传输
                httpHeaders.set(HttpHeaders.TRANSFER_ENCODING, "chunked");
                return httpHeaders;
            }
        };
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
